/*******************************************************************************
 * Copyright (c) 2012 Daniele Parisi.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html
 * 
 * Contributors:
 *     Daniele Parisi
 *     neb.inf@gmail.com
 *     http://www.danieleparisi.com/
 ******************************************************************************/
package org.jxreport.core.views.table;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.jxreport.core.Row;
import org.jxreport.core.Table;
import org.jxreport.core.XMLUtils;
import org.jxreport.core.XMLValues;
import org.jxreport.core.views.ViewObject;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class TableView extends ViewObject {
	
	protected HashMap<String, List<String>> cols = new HashMap<String, List<String>>();
	protected int maxSize = 0;
	
	public TableView(Element tableElement, Table table) {
		super(tableElement, table);

		NodeList nl = tableElement.getElementsByTagName(XMLValues.COL);
		for(int i = 0 ; i < nl.getLength();i++) {
			Element colElement = (Element)nl.item(i);
			
			List<String> values = new ArrayList<String>();
			String header = XMLUtils.getTextValue(colElement, XMLValues.HEADER);
			NodeList nl2 = tableElement.getElementsByTagName(XMLValues.VALUE);
			for (int j = 0; j < nl2.getLength(); j++) {
				Element valueElement = (Element)nl2.item(j);
				values.add(valueElement.getTextContent());
			}
			
			this.cols.put(header, values);
			if(values.size() > this.maxSize) this.maxSize = values.size();
		}
		
		nl = tableElement.getElementsByTagName(XMLValues.DATA_COL);
		for(int i = 0 ; i < nl.getLength();i++) {
			Element dataColElement = (Element)nl.item(i);
			String header = XMLUtils.getTextValue(dataColElement, XMLValues.HEADER);
			int valueIndex = XMLUtils.getIntValue(dataColElement, XMLValues.VALUE_INDEX);
			
			List<String> values = new ArrayList<String>();
			for (Row row : table) {
				Object value = row.get(valueIndex).getValue();
				if(value instanceof String)
					values.add((String)value);
				else if(value instanceof Double)
					values.add(String.valueOf((Double)value));
			}
			
			this.cols.put(header, values);
			if(values.size() > this.maxSize) this.maxSize = values.size();
		}
	}

	public HashMap<String, List<String>> getCols() {
		return cols;
	}

	public void setCols(HashMap<String, List<String>> cols) {
		this.cols = cols;
	}
}
